package com.eryos.android.cigarettecounter.database;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Project : CigaretteCounter Author : Olivier Combe URL : http://eryos.fr/CigaretteCounter/
 * 
 * Copyright(C)2011 - Olivier Combe
 * 
 * Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * 
 * @version \$Revision.*\$
 * @author Olivier Combe
 */
public class DBConnector {

    /** Logger Tag. */
    private static final String TAG = "DBConnector";

    private final Context context;
    private DatabaseAdministrator dbHelper;

    /** Current database. */
    protected SQLiteDatabase db;

    /** Name of the dababase file. */
    public static final String DATABASE_NAME = "eryos.db";
    /** Version of the dababase. */
    public static final int DATABASE_VERSION = 8;

    /** DB Main Table. */
    public static final String DATABASE_TABLE = "smoke_table";
    /** ROWID Column name. */
    public static final String ROWID_COLUMN = "_id";
    /** Time Column name. */
    public static final String TIME_COLUMN = "smoke_time";
    /** Reason Column name. */
    public static final String REASON_COLUMN = "smoke_reason";
    /** Price Column name. */
    public static final String PRICE_COLUMN = "smoke_valid";

    /**
     * SQL Create statement.
     */
    public static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE + "(" + ROWID_COLUMN
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TIME_COLUMN + " DATETIME DEFAULT CURRENT_TIMESTAMP, "
            + REASON_COLUMN + " TEXT," + PRICE_COLUMN + " TEXT" + ");";

    /**
     * SQL Drop statement.
     */
    public static final String DATABASE_DROP = "DROP TABLE IF EXISTS " + DATABASE_TABLE;

    /**
     * Default constructor.
     * 
     * @param ctx
     *            application context
     */
    public DBConnector(final Context ctx) {
        this.context = ctx;

        open();
    }

    /**
     * Open the Database connection.
     * 
     * @return DBConnector used to request database
     * @throws SQLException
     *             in case of error
     */
    public final DBConnector open() throws SQLException {
        if (db == null || !db.isOpen()) {
            Log.w(getClass().getSimpleName(), "Open DB connection");
            dbHelper = new DatabaseAdministrator(context);
            db = dbHelper.getWritableDatabase();
        }
        return this;
    }

    /**
     * Close the connection to Database.
     */
    public void close() {
        if (db.isOpen()) {
            Log.w(getClass().getSimpleName(), "Close DB connection");
            db.close();
            dbHelper.close();
        }
    }

    /** ************************************************************************** **/

    /**
     * Execute the given SQL query.
     * 
     * @param sql
     *            query to execute.
     * @return Cursor representing result of the execution
     */
    public Cursor executeQuery(final String sql) {
        return db.rawQuery(sql, null);
    }

    /** ************************************************************************** **/

    /**
     * Used for DDL operation on database(create, update, delete).
     */
    private static class DatabaseAdministrator extends SQLiteOpenHelper {
        /**
         * @param context
         *            of the application
         */
        DatabaseAdministrator(final Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(final SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
                    + ", which will destroy all old data");
            db.execSQL(DATABASE_DROP);
            onCreate(db);
        }
    }
}
